// pages/reviewRecord/spellword/spellWord.js
const app = getApp();
// let tool = require('../../../utils/tool.js');
const httpUtils = require('../../../utils/httpUtils.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    percent: 0,
    totalNum: 0,
    errNum: 0,
    imageUrl: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/',
    gameSecond: 50,
    gameSecond2: 50,
    timer: '',
    worldList: {},
    curWord: {},
    spellWord: '',
    curIndex: 0,
    innerAudioContext: new Object(),
    maskDis: 'flex',
    jbDis: 'flex',
    maskcompletDis: 'none',
    ggDis: 'none',
    gfDis: 'none',
    curSplit: -1,
    choiceArr: [],
    spellWrongTime: 0,
    errword: [],
    allword: [],
    rightWord: [],
    res_img: 'fuxi_xhjc_dui_press@2x.png',
    res_color: "",
    res_dis: "false",
    ishide: '1',  //页面是否隐藏，如黑屏
    date: '', //学习日期
    sort: '4', //作业形式 1 词义闯关 2 对对碰 3 廷议释义 4 组合拼 5读一遍 6 写一遍
    task_id: '', //任务id
    replayFlag: false,
    isNextPassFlag: false,
    can_submit: 1, //1 可以提交 0不可以提交

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.totalInit();
    let that = this;
    //获取传过来的日期
    that.setData({
      task_id: options.task_id,
      date: options.date,
      can_submit: options.can_submit
    })
    console.log(that.data.date)
    this.data.innerAudioContext = wx.createInnerAudioContext()
    this.data.innerAudioContext.autoplay = false;
    this.data.innerAudioContext.loop = false;

    this.getData();
    that.data.curIndex = 0;
    clearInterval(that.data.timer);
  },


  //设置描述
  setSec: function (e) {
    let that = this;
    if (!that.data.replayFlag) {
      console.log("选时间，下一关")
      that.setData({
        maskDis: 'none',
        jbDis: 'none',
        gfDis: 'none',
        gameSecond2: (e.currentTarget.dataset.passsce >= 10) ? e.currentTarget.dataset.passsce : ("0" + e.currentTarget.dataset.passsce),
        gameSecond: (e.currentTarget.dataset.passsce >= 10) ? e.currentTarget.dataset.passsce : ("0" + e.currentTarget.dataset.passsce)
      });
      that.daojishi('pass');
    } else {
      console.log("选时间，重玩本关")
      that.setData({
        maskDis: 'none',
        jbDis: 'none',
        gfDis: 'none',
        errNum: 0,
        spellWord: '',
        curIndex: 0,
        curSplit: -1,
        timer: '',
        choiceArr: [],
        spellWrongTime: 0,
        errword: [],
        rightWord: [],
        res_dis: "false",
        gameSecond2: (e.currentTarget.dataset.passsce >= 10) ? e.currentTarget.dataset.passsce : ("0" + e.currentTarget.dataset.passsce),
        gameSecond: (e.currentTarget.dataset.passsce >= 10) ? e.currentTarget.dataset.passsce : ("0" + e.currentTarget.dataset.passsce)
      });

      clearInterval(that.data.timer);
      if (this.data.gameSecond2 > 0) {
        console.log("开始倒计时")
        that.daojishi('pass');
      }
    }
  },

  nextPass: function () {
    clearInterval(this.data.timer);
    if (this.data.curIndex < this.data.worldList.length) {
      this.setData({
        gameSecond: this.data.gameSecond2
      });
      this.setData({ //初始化
        curWord: this.data.worldList[this.data.curIndex],
        spellWord: '',
        choiceArr: [],
        curSplit: -10,
        spellWrongTime: 0,
        curIndex: this.data.curIndex,
        gameSecond: this.data.gameSecond2,
      });
      console.log("当前单词:"+this.data.curWord.word)
      this.data.curIndex = this.data.curIndex + 1;
      this.playmp3(this.data.curWord.vedio_url);
    } else { //答题完毕
      clearInterval(this.data.timer);
      console.log("答题完毕了，看看是否判断弹窗")
      return;
    }
  },
  choice: function (e) {
    let that = this;
    if (this.data.choiceArr.indexOf(e.currentTarget.dataset.idx) == -1) {
      let tmp = this.data.choiceArr;
      tmp.push(e.currentTarget.dataset.idx);
      let spworld = this.data.spellWord + e.currentTarget.dataset.subw
      this.setData({
        choiceArr: tmp,
        spellWord: spworld
      })
      if (this.data.spellWord == this.data.curWord.word) { //拼对了
        this.playmp3(app.globalData.mp3.doright)
        clearInterval(this.data.timer);
        this.setData({
          res_img: 'fuxi_xhjc_dui_press@2x.png',
          res_dis: 'false',
          res_color: '#27BFA3',
  
        })

        // this.data.rightWord.push(this.data.curWord.id);
        //第一次做错就算错，判断拼错的下次数，如果错误次数为0，这个单词才是真的第一次就是拼对的
        if (this.data.spellWrongTime === 0) {
          this.data.rightWord.push(that.data.curWord.word);
        }

        setTimeout(function () {
          that.daojishi('pass')
        }, 1000);
      }

      if (this.data.choiceArr.length == this.data.curWord.split.length) {
        this.setData({
          res_img: 'fuxi_xhjc_cuo_press@2x.png',
          res_dis: 'false',
          res_color: '#FF6767'
        })
        //判断错误的次数，一次词拼错三次的话自动跳转下一个
        this.playmp3(app.globalData.mp3.selectwrong);
        if (this.data.spellWrongTime < 2) {
          this.data.spellWrongTime = this.data.spellWrongTime + 1;

          app.vibrateShortTap();
          setTimeout(function () {
            that.cancel();
          }, 1000);

        } else {
          //错误效果 抖动   音效
          clearInterval(this.data.timer);
          app.vibrateShortTap();
          setTimeout(function () {
            that.daojishi('pass');
          }, 1000);

        }

      }

    }
    this.setData({
      curSplit: e.currentTarget.dataset.idx
    })
  },
  cancel: function () {
    let that=this;
    console.log("取消图片显示r+es_dis："+that.data.res_dis)
    this.setData({
      spellWord: '',
      curSplit: -1,
      choiceArr: [],
      res_dis:'none',
      res_color: '#333333'
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("spellword界面onShow")
    let that = this;
    if (that.data.ishide == 2) {
      that.setData({
        ishide: 1
      })
      that.daojishi("");
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log("spellword界面onHide")
    this.setData({
      ishide: 2
    })
    clearInterval(this.data.timer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.totalInit();
    clearInterval(this.data.timer);
    this.data.innerAudioContext.stop();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 获取数据
   */
  getData: function () {
    var that = this;
    wx.showLoading({
      title: '',
      mask: true
    })
    httpUtils.getWordComposeReview({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      calendar_id: that.data.task_id,
    }).then((res) => {
      wx.hideLoading();
      let list = res.data;
      for (let ele of list) {
        that.data.allword.push(ele.word);
      }
      that.setData({
        worldList: list,
        totalNum: list.length
      })

    });
  },

  daojishi: function (flag = '') {
    console.log("-----daojishi-----flag=" + flag)
    this.setData({
      res_img: 'fuxi_xhjc_dui_press@2x.png',
      res_dis: 'none',
      res_color: '#333333'
    })
    let that = this;
    clearInterval(this.data.timer);
    //判断是否为最后一题答完了
    if (that.data.curIndex == that.data.worldList.length) {
      clearInterval(this.data.timer);
      that.judgeAndPop();
      //提交数据
      // that.submitAnswer();
      return false;
    }
    if (flag == 'pass') {
      that.nextPass();
    }
    that.data.timer = setInterval(function () {
      app.globalData.taskTwoMinuts = app.globalData.taskTwoMinuts + 1;
      let num = parseInt(that.data.gameSecond) - 1
      if (num >= 0) {
        if (num < 10 && num >= 0) {
          num = "0" + num.toString();
        }
        that.setData({
          gameSecond: num
        });
      } else {
        clearInterval(that.data.timer);
  
      }

      if (parseInt(that.data.gameSecond) <= 0) {
        clearInterval(that.data.timer);
        that.daojishi('pass');
      }
    }, 1000);
  },

  //判断是否通关，并弹对应的弹窗
  judgeAndPop() {
    let that = this;
    that.collectWrong();
    let num = parseInt((that.data.totalNum) / 2);
    let errNum = that.data.errNum;
    console.log("计算错词并比较，标准num=" + num + "，errnum=" + errNum + ",错词为：" + that.data.errword)
    if (errNum > num) {
      that.setData({
        gfDis: 'flex',
        ggDis:'none',
        maskcompletDis: 'flex',
        replayFlag: true
      });
    } else {
      that.setData({
        ggDis: 'flex',
        gfDis:'none',
        maskcompletDis: 'flex',
        replayFlag: false
      });
    }
  },


  //播放音
  playmp3: function (mp3url) { //播放音效
    this.data.innerAudioContext.src = mp3url;
    this.data.innerAudioContext.play();

  },
  replay: function () {
    this.playmp3(this.data.curWord.vedio_url);
  },


  //提交答案
  submitAnswer: function () {
    let that = this;
    // that.collectWrong();
    wx.showLoading({
      title: '正在提交',
      mask: true
    })
    console.log("提交的时候的错词为：", JSON.stringify(this.data.errword));
    httpUtils.submitWordReview({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      calendar_id: that.data.task_id,
      sort: that.data.sort,
      pic: "",
      stu_answer: "",
      allword: that.data.allword.join(','),
      errword: that.data.errword.join(','),

    }).then((res) => {
      wx.hideLoading();
      console.log("提交成功")
      let remainword = res.data.remain;
      if (remainword <= 0) {
        console.log("剩余单词数小于等于0了，提交完成直接跳报告页")
        setTimeout(function () {
          wx.showToast({
            title: "恭喜你完成复习~",
            icon: 'none',
            duration: 2000
          });
        }, 500)
        wx.redirectTo({
          url: '../playReport/playReport?task_id=' + that.data.task_id + "&sort=" + that.data.sort + "&can_submit=" + that.data.can_submit + "&date=" + that.data.date + "&type=0",
        })
        return false;
      }

      console.log("提交成功~isNextPassFlag=" + that.data.isNextPassFlag)
      if (that.data.isNextPassFlag) {
        console.log("初始化数据，并获取下一关的数据")
        that.totalInit();
        that.getData();
        // if (this.data.gameSecond2 > 0) {
        //   that.daojishi();
        // }
      }else{
        console.log("点不想玩了，提交成功，跳转报告页")
        wx.redirectTo({
          url: '../playReport/playReport?task_id=' + that.data.task_id + "&sort=" + that.data.sort + "&can_submit=" + that.data.can_submit + "&date=" + that.data.date + "&type=0",
        })
      }

    });

  },


  //点击弹窗中的继续闯关按钮
  nextLevel: function () {
    let that = this;
    console.log("点击继续闯关按钮，开启下一关")
    that.setData({
      isNextPassFlag: true
    })
    clearInterval(that.data.timer);
    that.submitAnswer();
 
  },

  //点击弹窗中重玩本关的按钮
  playAgain: function () {
    console.log("点击重玩本关按钮")
    let that = this;
    clearInterval(that.data.timer);
    that.setData({
      maskDis: 'flex',
      jbDis: 'flex',
      maskcompletDis: 'none',
      gfDis: 'none',
      ggDis: 'none',

    })

  },

  //点击弹窗中的 不想玩了按钮
  toReport() {
    console.log("不想玩了")
    let that = this;
    that.setData({
      maskcompletDis: 'none',
      maskDis: 'none',
      jbDis: 'none',
      maskDis: 'none',
      jbDis: 'none',
      isNextPassFlag: false
    })
    that.submitAnswer();

  },

  // 加入错词
  collectWrong: function () {
    let that = this;
    for (let ele of that.data.allword) {
      if (this.data.rightWord.indexOf(ele) == -1) {
        this.data.errword.push(ele)
      }
    }
    that.setData({
      errNum: that.data.errword.length
    })
  },
  totalInit: function () {
    clearInterval(this.data.timer);
    this.setData({
      percent: 0,
      totalNum: 0,
      errNum: 0,
      imageUrl: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/',
      gameSecond: 50,
      gameSecond2: 50,
      timer: '',
      worldList: {},
      curWord: {},
      spellWord: '',
      curIndex: 0,
      maskDis: 'flex',
      jbDis: 'flex',
      gfDis: 'none',
      maskcompletDis:'none',
      ggDis:'none',
      curSplit: -1,
      choiceArr: [],
      spellWrongTime: 0,
      errword: [],
      allword: [],
      rightWord: [],
      res_img: 'fuxi_xhjc_dui_press@2x.png',
      res_color: "",
      res_dis: "false"
    })

  }
})